#include "mainwindowimpl.h"
//
MainWindowImpl::MainWindowImpl( QWidget * parent, Qt::WFlags f) 
        : QMainWindow(parent, f) , server_(this)
{
	setupUi(this);
        widget->hide();
        this->setWindowIcon( QIcon(":/cta/icons/cta.png") );
	ssd = new StartServerDialogImpl;
        systray = new systemTray(this);
        connect ( action_Start_Server, SIGNAL(triggered()), ssd, SLOT( exec()) );
        connect ( ssd->pushButton, SIGNAL(clicked()), this, SLOT(setServerName()) );
        connect ( ssd->pushButton, SIGNAL(clicked()), this, SLOT(setServerPort()) );
        connect ( ssd->pushButton, SIGNAL(clicked()), this, SLOT(setServerLevel()) );
        connect ( ssd->pushButton, SIGNAL(clicked()), ssd, SLOT(close()) );
        connect ( ssd->pushButton, SIGNAL (clicked()), widget, SLOT(show()) );
        connect ( ssd->pushButton, SIGNAL(clicked()), this, SLOT(startServer()) );

        connect ( &server_, SIGNAL(newConnection()), this, SLOT(getNewConnectionIP()) );
        connect ( &httpserver_, SIGNAL (newConnection()), this, SLOT(sendHttpData()) );
        connect ( disconnectButton, SIGNAL(clicked()), this, SLOT(Disconnect()) );
        connect ( &server_, SIGNAL(clientsUpdated()), this, SLOT(createList()) );
}

void MainWindowImpl::setServerName()
{
    server_.ServerName = ssd->lineEdit->text();
    httpserver_.ServerName = ssd->lineEdit->text();
    serverNameLineEdit->setText(ssd->lineEdit->text());
    this->setWindowTitle("CTA Server - "+ssd->lineEdit->text());
}

void MainWindowImpl::setServerPort()
{
    server_.ServerPort = ssd->spinBox->value();
    server_.ServerInfoPort = ssd->infoPortBox->value();
    httpserver_.ServerPort = ssd->infoPortBox->value();
}

void MainWindowImpl::setServerLevel()
{
    QFileInfo LevelInfo(ssd->levelLineEdit->text());
    if(!LevelInfo.exists()) return;

    server_.ServerLevel = LevelInfo.filePath();
    server_.ServerLevelName = LevelInfo.fileName();
}

bool MainWindowImpl::startServer()
{
    if((server_.startServer()==true)&&(httpserver_.startServer()==true))
    {
        server_.start();
        return true;
    }
    return false;
}

void MainWindowImpl::getNewConnectionIP()
{
    createList();
}

void MainWindowImpl::createList()
{
    clientsListWidget->clear();
    for(int i=0; i < server_.client.size(); ++i)
    {
        clientsListWidget->addItem(server_.client[i]->NickName);
    }
}

void MainWindowImpl::sendHttpData()
{
    QString str;
    str.append("<html><head><title>").append(httpserver_.ServerName);
    str.append(" - CatchTheAlien Server</title></head><body>");
    for(int i=0; i<clientsListWidget->count() ;i++)
    {
        str.append("<p>");
        str.append(clientsListWidget->item(i)->text());
    }
    str.append("</body></html>");
    httpserver_.SendSite(str);
    httpserver_.Disconnect();
}

void MainWindowImpl::Disconnect()
{
    server_.Disconnect(clientsListWidget->currentRow());
}
//
